<template>
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData, readonly }"
    :api-map="discussLogListCRUD"
    header="*洽商变更"
    width="60%"
    :on-before-set-data="handleDialogSetData"
    :on-before-save-data="handleDialogSaveData"
    @request-success="handleDialogRequestSuccess"
  >
  <t-row :gutter="[20, 20]" style="width: 100%">
        <t-col :span="3">
          <t-form-item label="洽商类型" name="discussLogType" :rules="[{ required: true, message: '请选择洽商类型' }]">
            <t-select 
              v-model:value="formData.discussLogType" 
              :options="dictionaryStore.get('discuss_log_type')" 
              clearable
              filterable 
              placeholder="" 
              :readonly="readonly"
              @change="handleChangeDiscussLogType"
            />
          </t-form-item>
        </t-col>
        <t-col :span="3">
          <t-form-item label="洽商时段" name="discussTimeType" :rules="[{ required: true, message: '请选择洽商时段' }]">
            <t-select 
              v-model:value="formData.discussTimeType" 
              :options="dictionaryStore.get('discuss_time_type')" 
              clearable
              filterable 
              :readonly="readonly"
              placeholder="" 
            />
          </t-form-item>
        </t-col>
        <t-col :span="3">
          <t-form-item label="延期天数" name="extensionDay" :rules="[{ required: true, message: '请输入延期天数' }]">
            <t-input v-model:value="formData.extensionDay" placeholder="请输入延期天数" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="3">
          <t-form-item label="收款阶段" name="paymentStage" :rules="[{ required: true, message: '请输入收款阶段' }]">
            <t-input v-model:value="formData.paymentStage" placeholder="请输入收款阶段" clearable :readonly="true" @click="handleSelectPaymentStage(readonly)" />
          </t-form-item>
        </t-col>
        <t-col :span="3">
          <t-form-item label="洽商变更单据" name="fileUrl" :rules="[{ required: true, message: '请上传洽商变更单据' }]">
            <upload 
              v-model:files="formData.fileUrl" 
              accept="image/*" 
              theme="image" 
              :disabled="readonly"
              multiple
              />
          </t-form-item>
        </t-col>
      </t-row>
      <div v-if="['1','2','3'].includes(formData.discussLogType)">
        <t-divider>增项</t-divider>
        <div style="width: 100%">
          <t-table
            row-key="id"
            :data="formData.costList"
            :columns="columnsProgramme"
            bordered
            hover
            size="small"
            stripe
          >
            <template #number="{ row, rowIndex }">
              <t-form-item
                label="数量"
                :name="`costList[${rowIndex}].number`"
                :rules="[{ required: true, message: '请输入数量' }]"
                label-width="0"

              >
              <t-input-number
                v-model:value="row.number"
                placeholder="请输入数量"
                clearable
                :readonly="readonly"
                style="width: 100%"
                :min="1"
                :decimal-places="2"
                @change="(val)=>handleChangeNum(val,row)"
            
              />
              </t-form-item>
            </template>
          
            <template #unit="{ row, rowIndex }">
              <t-form-item
                label="单位"
                :name="`costList[${rowIndex}].unit`"
                :rules="[{ required: false, message: '请输入单位' }]"
                label-width="0"
              >
              {{dictionaryStore.analysis('unit', row.unit)}}
              </t-form-item>
            </template>
          
            <template #operation="{ rowIndex }">
              <t-popconfirm
                v-if="!readonly"
                content="确认要删除该项吗？"
                @confirm="handleDeleteRow(rowIndex,'costList')"
              >
                <t-link theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </template>
          </t-table>
          <t-button v-if="!readonly" block @click="handleSelectAdd(formData.discussLogType,'costList')" > 添加增项 </t-button>
        </div>
        <t-divider>减项</t-divider>
        <div style="width: 100%">
          <t-table
            row-key="id"
            :data="formData.reduceList"
            :columns="columnsProgramme"
            bordered
            size="small"
            stripe
            hover
          >
            <template #number="{ row, rowIndex }">
              <t-form-item
                label="数量"
                :name="`reduceList[${rowIndex}].number`"
                :rules="[{ required: true, message: '请输入数量' }]"
                label-width="0"

              >
              <t-input-number
                v-model:value="row.number"
                placeholder="请输入数量"
                clearable
                :readonly="readonly"
                style="width: 100%"
                :min="1"
                :decimal-places="2"
                @change="(val)=>handleChangeNum(val,row)"
            
              />
              </t-form-item>
            </template>
          
            <template #unit="{ row, rowIndex }">
              <t-form-item
                label="单位"
                :name="`reduceList[${rowIndex}].unit`"
                :rules="[{ required: false, message: '请输入单位' }]"
                label-width="0"
              >
              {{dictionaryStore.analysis('unit', row.unit)}}
              </t-form-item>
            </template>
          
            <template #operation="{ rowIndex }">
              <t-popconfirm
                v-if="!readonly"
                content="确认要删除该项吗？"
                @confirm="handleDeleteRow(rowIndex,'reduceList')"
              >
                <t-link theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </template>
          </t-table>
          <t-button v-if="!readonly" block @click="handleSelectAdd(formData.discussLogType,'reduceList')" > 添加减项 </t-button>
        </div>

      </div>
      <div v-if="['4'].includes(formData.discussLogType)">
        <t-divider>新项</t-divider>
        <div style="width: 100%">
          <t-table
            row-key="id"
            :data="formData.costList"
            :columns="columnsModel"
            bordered
            size="small"
            stripe
            hover
          >
            <template #number="{ row, rowIndex }">
              <t-form-item
                label="数量"
                :name="`costList[${rowIndex}].number`"
                :rules="[{ required: true, message: '请输入数量' }]"
                label-width="0"

              >
              <t-input-number
                v-model:value="row.number"
                placeholder="请输入数量"
                clearable
                :readonly="readonly"
                style="width: 100%"
                :min="1"
                :decimal-places="2"
                @change="(val)=>handleChangeNum(val,row)"
            
              />
              </t-form-item>
            </template>
          
            <template #unit="{ row, rowIndex }">
              <t-form-item
                label="单位"
                :name="`costList[${rowIndex}].unit`"
                :rules="[{ required: false, message: '请输入单位' }]"
                label-width="0"
              >
              {{dictionaryStore.analysis('unit', row.unit)}}
              </t-form-item>
            </template>
            <template #color="{ row, rowIndex }">
              <t-form-item
                label="颜色"
                :name="`costList[${rowIndex}].color`"
                :rules="[{ required: false, message: '请输入颜色' }]"
                label-width="0"

              >
              <t-input
                v-model:value="row.color"
                placeholder="请输入颜色"
                clearable
                :readonly="readonly"
              />
              </t-form-item>
            </template>  
          
            <template #operation="{ rowIndex }">
              <t-popconfirm
                v-if="!readonly"
                content="确认要删除该项吗？"
                @confirm="handleDeleteRow(rowIndex,'costList')"
              >
                <t-link theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </template>
          </t-table>
          <t-button v-if="!readonly" block @click="handleSelectAdd(formData.discussLogType,'costList')" > 添加新项 </t-button>
        </div>
        <t-divider>旧项</t-divider>
        <div style="width: 100%">
          <t-table
            row-key="id"
            :data="formData.reduceList"
            :columns="columnsModel"
            bordered
            size="small"
            stripe
            hover
          >
            <template #number="{ row, rowIndex }">
              <t-form-item
                label="数量"
                :name="`reduceList[${rowIndex}].number`"
                :rules="[{ required: true, message: '请输入数量' }]"
                label-width="0"

              >
              <t-input-number
                v-model:value="row.number"
                placeholder="请输入数量"
                clearable
                :readonly="readonly"
                style="width: 100%"
                :min="1"
                :decimal-places="2"
                @change="(val)=>handleChangeNum(val,row)"
            
              />
              </t-form-item>
            </template>
          
            <template #unit="{ row, rowIndex }">
              <t-form-item
                label="单位"
                :name="`reduceList[${rowIndex}].unit`"
                :rules="[{ required: false, message: '请输入单位' }]"
                label-width="0"
              >
              {{dictionaryStore.analysis('unit', row.unit)}}
              </t-form-item>
            </template>
            <template #color="{ row, rowIndex }">
              <t-form-item
                label="颜色"
                :name="`reduceList[${rowIndex}].color`"
                :rules="[{ required: false, message: '请输入颜色' }]"
                label-width="0"

              >
              <t-input
                v-model:value="row.color"
                placeholder="请输入颜色"
                clearable
                :readonly="readonly"
              />
              </t-form-item>
            </template>
          
            <template #operation="{ rowIndex }">
              <t-popconfirm
                v-if="!readonly"
                content="确认要删除该项吗？"
                @confirm="handleDeleteRow(rowIndex,'reduceList')"
              >
                <t-link theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </template>
          </t-table>
          <t-button v-if="!readonly" block @click="handleSelectAdd(formData.discussLogType,'reduceList')" > 添加旧项 </t-button>
        </div>
      </div>
  </custom-dialog>
  <!-- 选择收款对话框 -->
  <discuss-collection-id-selector 
    v-if="isOpenCollection"
    v-model:visible="visibleCollection"
    :order-id="props.orderId"
    @save="handleSaveCollection"/>
  <!-- 选择项目对话框 -->
  <discuss-programme-selector-dialog 
    v-model:visible="visibleProgramme"
    @save="handleSaveProgramme"
   />
     <!-- 主材 -->
    <cost-selection-dialog
      v-model:visible="visibleMaterial"
      :type="'1'"
      @save="handleSaveMaterial"
     />
     <!-- 产品 -->
    <discuss-product-selector-dialog
      v-model:visible="visibleProduct"
      :order-id="props.orderId"
      @save="handleSaveProduct" 
    />
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';
import { TableCol } from 'tdesign-vue-next';
import { discussLogListCRUD } from '@/api/project/details';
import { payContractZhengCRUD } from '@/api/finance/pay';
import CustomDialog from '@/components/custom/dialog/index.vue';
import DiscussProgrammeSelectorDialog from '@/pages/project/details/components/DiscussProgrammeSelectorDialog.vue';
import CostSelectionDialog from '@/pages/budget/programme/components/CostSelectionDialog.vue';
import DiscussProductSelectorDialog from '@/pages/project/details/components/DiscussProductSelectorDialog.vue';
import DiscussCollectionIdSelector from '@/pages/project/details/components/DiscussCollectionIdSelector.vue';
import Upload from '@/components/upload/index.vue';

import { useDictionaryStore } from '@/store';

const props = defineProps({
  orderId: {
    type: String,
    required: true,
  },
  isOpenCollection: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(['requestSuccess']);
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');

// 选择收款阶段
const handleSelectPaymentStage = (readonly:any) =>{
  if(readonly||!props.isOpenCollection) return
  visibleCollection.value = true
}
// 选择收款阶段
const visibleCollection = ref(false)
// 收款选择完成
const handleSaveCollection = (selectedItem:any) => {
  customDialogRef.value.formData.collectionId = selectedItem.collectionId
  customDialogRef.value.formData.paymentStage = selectedItem.paymentStage
}
// 弹框的前3种洽商类型的column
const columnsProgramme: TableCol[] = [
  { colKey: 'projectName', title: '项目名称' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'number', title: '数量' },
  { colKey: 'unitPrice', title: '单价(元)' },
  { colKey: 'totalPrice', title: '总价(元)' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
// 弹框的第4种洽商类型的column
const columnsModel: TableCol[] = [
  { colKey: 'projectName', title: '项目名称' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'model', title: '型号' },
  { colKey: 'specifications', title: '规格',width:100 },
  { colKey: 'color', title: '颜色' },
  { colKey: 'number', title: '数量',width:180 },
  { colKey: 'unitPrice', title: '单价(元)' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
const listType = ref('costList')
const discussLogType = ref('')
// 添加增项(选择项目-基础洽商)
const handleSelectAdd = (type:string,list:any) => {
  if(type==='1') {
    visibleProgramme.value = true
  } else if(type==='2' || type==='4') {
    visibleMaterial.value = true
  } else if(type==='3') {
    visibleProduct.value = true
  } 
  listType.value = list
  discussLogType.value = type
}
// 选择项目-基础洽商
const visibleProgramme = ref(false)
const discussType = ref('')
const handleSaveProgramme = (selectedData: any[]) => {

  if(listType.value == 'costList') {
    discussType.value ='1'
  } else if(listType.value == 'reduceList') {
    discussType.value ='2'
  }
  selectedData.forEach(item => {
    item.discussType = discussType.value
  })
    // 过滤掉已存在的数据
    const newData = selectedData.filter((selectedItem) => {
    return !customDialogRef.value.formData[listType.value].some((existingItem:any) => existingItem.materialsId == selectedItem.materialsId);
  });
  customDialogRef.value.formData[listType.value] = [...customDialogRef.value.formData[listType.value], ...newData]
}
const handleChangeNum = (val:any,row:any) => {
  row.totalPrice= (row.unitPrice*val).toFixed(2)
}
const handleDeleteRow = (rowIndex: number,list:any) => {
  customDialogRef.value.formData[list].splice(rowIndex, 1)
}
// 选择主材
const visibleMaterial = ref(false)
const handleSaveMaterial = (selectedData: any[]) => {

  const itemType = ref('')
  if(discussLogType.value == '2') {
    // 主材增项1减项2
    itemType.value = 'discussType'
    if(listType.value == 'costList') {
      discussType.value ='1'
    } else if(listType.value == 'reduceList') {
      discussType.value ='2'
    }
  } else if(discussLogType.value == '4') {
    // 模型原材料1 新材料2
    itemType.value = 'newOrOld'
    if(listType.value == 'costList') {
      discussType.value ='2'
    } else if(listType.value == 'reduceList') {
      discussType.value ='1'
    }
  }
  selectedData.forEach(item => {
    item.projectName = item.name
    item.unitPrice = item.sellingPrice
    item[itemType.value] = discussType.value

  })
    // 过滤掉已存在的数据
    const newData = selectedData.filter((selectedItem) => {
    return !customDialogRef.value.formData[listType.value].some((existingItem:any) => existingItem.materialsId == selectedItem.materialsId);
  });
  customDialogRef.value.formData[listType.value] = [...customDialogRef.value.formData[listType.value], ...newData]
}
const handleChangeDiscussLogType = () => {
  customDialogRef.value.formData.costList = []
  customDialogRef.value.formData.reduceList = []
}
// 选择产品
const visibleProduct = ref(false)
const handleSaveProduct= (selectedData: any[]) => {
  if(listType.value == 'costList') {
    discussType.value ='1'
  } else if(listType.value == 'reduceList') {
    discussType.value ='2'
  }
  selectedData.forEach(item => {
    item.discussType = discussType.value
  })
  // 过滤掉已存在的数据
  const newData = selectedData.filter((selectedItem) => {
    return !customDialogRef.value.formData[listType.value].some((existingItem:any) => existingItem.materialsId == selectedItem.materialsId);
  });
  customDialogRef.value.formData[listType.value] = [...customDialogRef.value.formData[listType.value], ...newData]
}
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  if(params.discussLogType==='1' ||params.discussLogType==='2' || params.discussLogType==='3') {
    params.foundationDiscussList=[...params.costList,...params.reduceList]
  } else if(params.discussLogType==='4') {
    params.mainMaterialsModelDiscussList=[...params.costList,...params.reduceList]
  }
  delete params.costList
  delete params.reduceList
};
// 收款阶段
const collectionAllList = ref<Record<string, any>[]>([]);
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  if(params.foundationDiscussList.length>0) {
    params.costList= params.foundationDiscussList.filter((item:any) => item.discussType === "1")
    params.reduceList= params.foundationDiscussList.filter((item:any) => item.discussType === "2")
  }
  if(params.mainMaterialsModelDiscussList.length>0) {
    params.costList= params.mainMaterialsModelDiscussList.filter((item:any) => item.newOrOld === "2")
    params.reduceList= params.mainMaterialsModelDiscussList.filter((item:any) => item.newOrOld === "1")
  }
  if(params.collectionId) {
   
      const target = collectionAllList.value.find((item:any) => item.id === params.collectionId)
      params.paymentStage = target.paymentStage  
  }

};
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
}
const open = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  if(mode!=='create') {
    payContractZhengCRUD.page({orderId:props.orderId,pageSize:-1}).then(data => {
      collectionAllList.value = data
       customDialogRef.value.open(mode, params);
    })
  } else {
     customDialogRef.value.open(mode, params);
  }
};
defineExpose({
  open,
});
</script>
<style lang="less" scoped>
:deep(.t-upload__card) {
  flex-wrap: inherit
}

</style>